import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:netease_music/pages/search/buildSong/index.dart';
import 'package:netease_music/player/controller/audio_player_controller.dart';
import 'package:netease_music/theme/custom_colors.dart';
import 'package:netease_music/utils/real_api.dart';
import 'package:netease_music/widget/bottom_player_box.dart';
import 'package:netease_music/widget/my_loading.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final audioController = Get.find<AudioPlayerController>();
  // 焦点控制
  final FocusNode _focusNode = FocusNode();
  // 输入框控制器
  final _searchController = TextEditingController();
  // 是否显示清除icon
  bool _showClearIcon = false;
  // 是否显示搜索icon
  bool _showSearchIcon = true;
  // 默认组件和搜索组件的切换
  bool _showSearchDetail = false;
  // 热搜列表
  final List<String> hotWords = [
    '李白',
    '两难',
    '鹿晗',
    '嗨好',
    '天赐的声音',
    '爱情讯息',
    '莫愁乡',
    '零距离的思念',
    '天空没有极限',
    '跳楼机',
    '张杰',
  ];
  // tabs渲染列表
  final List<String> tabs = ['单曲', '歌手', '专辑', '歌单', 'MV', '主播电台', '用户'];
  // tabs对应请求类型
  final List<int> tabTypes = [1, 100, 10, 1000, 1004, 1009, 1002];
  // 每个tabs的总数据
  List<List<dynamic>> _tabResults = [];
  // 每个tabs防止重复加载
  List<bool> _isLoadingMore = [];
  // 每个tabs切换tabs只加载一次
  List<bool> _tabLoaded = [];
  // 每个tabs是否还有更多
  List<bool> _hasMore = [];
  // 每个tabs的数据总计是多少
  List<int> _limits = [];
  // 历史记录
  List<dynamic> _historyItems = [];
  @override
  void initState() {
    super.initState();
    // 初始化数据
    _initData();

    // 页面加载后自动获取焦点
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_focusNode);
      // 获取历史记录
      _getHistory();
    });
    _searchController.addListener(() {
      // 监听输入框变化
      setState(() {
        _showClearIcon = _searchController.text.isNotEmpty;
      });
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _initData() {
    _tabResults = List.generate(tabs.length, (_) => []);
    _tabLoaded = List.generate(tabs.length, (_) => false);
    _isLoadingMore = List.generate(tabs.length, (_) => false);
    _hasMore = List.generate(tabs.length, (_) => true);
    _limits = List.generate(tabs.length, (_) => 20);
  }

  void _getHistory() async {
    final prefs = await SharedPreferences.getInstance();
    final json = prefs.getString('searchHistory');
    if (json != null) {
      final searchHistory = jsonDecode(json);
      setState(() {
        _historyItems = searchHistory;
      });
    }
  }

  void _addNewItem() {
    if (_searchController.text.isEmpty) return;
    setState(() {
      final data = {
        'id': DateTime.now().millisecondsSinceEpoch.toString(),
        'name': _searchController.text
      };
      _historyItems.insert(0, data);
      _saveHistory();
    });
  }

  void _deleteItem(String id) {
    setState(() {
      _historyItems.removeWhere((item) => item['id'] == id);
    });
    _saveHistory();
  }

  Future<void> _saveHistory() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(
      'searchHistory',
      json.encode(_historyItems),
    );
  }

  void _clearText() {
    _searchController.clear();
    setState(() {
      _initData();
      _showSearchDetail = false; // 回到默认
      _showSearchIcon = true; // 展示搜索icon
    });
  }

  void searchBtn() {
    /**
     * 1.判断输入款是否有值
     * 2.切换搜索详情组件 隐藏搜索icon
     * 3.发送第一个请求
     * 4.将输入的值存入本地
     * 5.关闭焦点
     */
    if (!_showClearIcon) {
      return;
    }
    setState(() {
      _showSearchDetail = true; // 切换搜索详情组件
      _showSearchIcon = false; // 隐藏搜索icon
    });
    _fetchTabData(0);
    _addNewItem();
    FocusScope.of(context).unfocus();
  }

  Future<void> _fetchTabData(int index, {bool loadMore = false}) async {
    if (_isLoadingMore[index]) return; // 防止重复加载

    _isLoadingMore[index] = true;
    final type = tabTypes[index];
    final keyword = _searchController.text;

    try {
      final result = await RealApi.getCloudSearch(
        keyword,
        // 初始20条 下拉后加10条
        limit: _limits[index],
        type: type,
      );
      // 假设统一提取结果数组（你需要根据 type 判断字段路径，比如 result['songs']、result['playlists'] 等）
      final List<dynamic> items = _extractResultList(result, type);
      final int count = getResultListCount(result, type);
      if (mounted) {
        setState(() {
          if (loadMore) {
            _tabResults[index].addAll(items);
          } else {
            _tabResults[index] = items;
          }
          // 每次点击只加载一次数据
          _tabLoaded[index] = true;
          _limits[index] += 10;
          _hasMore[index] = _tabResults[index].length < count;
          // 防止重复请求
          _isLoadingMore[index] = false;
        });
      }
    } catch (e) {
      Get.snackbar('服务器错误', '$e');
      _isLoadingMore[index] = false;
    }
  }

  // 获取每个请求不同的数据格式
  List<dynamic> _extractResultList(dynamic data, int type) {
    final result = data['result'];

    if (result == null) return [];

    switch (type) {
      case 1:
        // 处理单曲数据
        return (result['songs'] as List?)
                ?.map(
                  (e) => {
                    'name': e['name'],
                    'artists':
                        (e['ar'] as List).map((it) => it['name']).toList(),
                    'mv': e['mv'],
                    'alblum': e['al']['name'],
                    'id': e['id'],
                    'picUrl': e['al']['picUrl'] ??
                        'https://p2.music.126.net/fM7vC38wA8N_EK7zMSHfpw==/109951170529173799.jpg',
                  },
                )
                .toList() ??
            [];
      case 10:
        return (result['albums'] as List?)
                ?.map((e) => e['name'] as String)
                .toList() ??
            [];
      case 100:
        return (result['artists'] as List?)
                ?.map((e) => e['name'] as String)
                .toList() ??
            [];
      case 1000:
        return (result['playlists'] as List?)
                ?.map((e) => e['name'] as String)
                .toList() ??
            [];
      case 1002:
        return (result['userprofiles'] as List?)
                ?.map((e) => e['nickname'] as String)
                .toList() ??
            [];
      case 1004:
        return (result['mvs'] as List?)
                ?.map((e) => e['name'] as String)
                .toList() ??
            [];
      case 1009:
        return (result['djRadios'] as List?)
                ?.map((e) => e['name'] as String)
                .toList() ??
            [];
      default:
        return [];
    }
  }

  // 获取每个请求不同的数据 总数量
  int getResultListCount(dynamic data, int type) {
    final result = data['result'];
    if (result == null) return 0;
    switch (type) {
      case 1:
        return result['songCount'] ?? 0;
      case 10:
        return result['albumCount'] ?? 0;
      case 100:
        return result['artistCount'] ?? 0;
      case 1000:
        return 30;
      case 1002:
        return 30;
      case 1004:
        return 30;
      case 1009:
        return 30;
      default:
        return 30;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: _buildLeading(),
        title: _buildSearchInput(),
      ),
      body: BottomPlayerBox(
        // 切换组件动画效果
        child: AnimatedSwitcher(
          duration: const Duration(milliseconds: 300),
          // 淡入淡出效果
          transitionBuilder: (Widget child, Animation<double> animation) {
            return FadeTransition(opacity: animation, child: child); // 淡入淡出动画
          },
          child: _showSearchDetail ? _buildSearchDetail() : _buildDefault(),
        ),
      ),
    );
  }

  // 默认展示
  Widget _buildDefault() {
    return CustomScrollView(
      key: const ValueKey("search_default"),
      physics: const BouncingScrollPhysics(), // 有回弹效果
      slivers: [
        //  歌手分类
        SliverToBoxAdapter(
          child: _buildSingerClassify(),
        ),
        // 热门搜索
        SliverToBoxAdapter(
          child: _buildHotList(),
        ),
        // 搜索历史
        SliverToBoxAdapter(
          child: _buildSearchHistory(),
        ),
      ],
    );
  }

  // 搜索详情组件
  Widget _buildSearchDetail() {
    return DefaultTabController(
      length: tabs.length,
      child: Column(
        key: const ValueKey('search_detail'),
        children: [
          Container(
            color: Theme.of(context).scaffoldBackgroundColor,
            child: TabBar(
              tabAlignment: TabAlignment.start,
              isScrollable: true,
              labelPadding: const EdgeInsets.symmetric(
                horizontal: 24,
              ), // 控制每个 Tab 项间距
              labelStyle: TextStyle(
                color: Theme.of(context).primaryColor,
                fontSize: 14,
              ),
              unselectedLabelStyle: Theme.of(context).textTheme.bodyMedium,
              indicatorSize: TabBarIndicatorSize.tab,
              indicator: UnderlineTabIndicator(
                borderSide: BorderSide(
                  width: 2,
                  color: Theme.of(context).primaryColor,
                ),
              ),
              tabs: tabs.map((e) => Tab(text: e)).toList(),
              onTap: (index) {
                if (!_tabLoaded[index]) {
                  _fetchTabData(index);
                }
              },
            ),
          ),
          Expanded(
            child: TabBarView(
              children: List.generate(tabs.length, (index) {
                return _buildTabContent(index);
              }),
            ),
          ),
        ],
      ),
    );
  }

  // 加载不同的数据和组件
  Widget _buildTabContent(int index) {
    final data = _tabResults[index];
    final controller = ScrollController();
    controller.addListener(() {
      if (controller.position.pixels >=
              controller.position.maxScrollExtent - 100 &&
          !_isLoadingMore[index] &&
          _hasMore[index]) {
        _fetchTabData(index, loadMore: true);
      }
    });

    return ListView.builder(
      controller: controller,
      itemCount: data.length + 1,
      itemBuilder: (_, i) {
        if (i < data.length) {
          if (index == 0) {
            return BuildSong(
              data: data[i],
              ontap: () {
                audioController.playSong(data[i]);
              },
            );
          } else {
            return const Text('测试');
          }
        } else if (_hasMore[index]) {
          return Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                MyLoading(
                  barCount: 4,
                  width: 2,
                  height: 24,
                  color: Theme.of(context).primaryColor,
                ),
                const SizedBox(
                  width: 6,
                ),
                Text(
                  '努力加载中...',
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
              ],
            ),
          );
        } else {
          return Padding(
            padding: const EdgeInsets.all(16),
            child: Center(
              child: Text(
                '已经到底部啦',
                style: Theme.of(context).textTheme.bodyMedium,
              ),
            ),
          );
        }
      },
    );
  }

  Widget _buildSingerClassify() {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: Container(
        padding: const EdgeInsets.symmetric(
          vertical: 4,
          horizontal: 0,
        ),
        decoration: BoxDecoration(
          border: Border.all(
            width: 1,
            color: Theme.of(context).extension<CustomColors>()!.borderColor,
          ),
          borderRadius: BorderRadius.circular(2),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.person,
              size: 24,
              color: Theme.of(context).extension<CustomColors>()!.borderColor,
            ),
            Text(
              '歌手分类',
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            Icon(
              Icons.chevron_right,
              size: 24,
              color: Theme.of(context).extension<CustomColors>()!.borderColor,
            )
          ],
        ),
      ),
    );
  }

  Widget _buildHotList() {
    return Container(
      padding: const EdgeInsets.only(
        bottom: 12,
        left: 12,
        right: 12,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text(
            '热门搜索',
            style: Theme.of(context).textTheme.bodyLarge,
          ),
          const SizedBox(
            height: 8,
          ),
          // 标签区域
          Wrap(
            spacing: 10,
            runSpacing: 10,
            children: hotWords.map((word) {
              return GestureDetector(
                onTap: () {
                  _searchController.text = word;
                  searchBtn();
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 6,
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Theme.of(context)
                          .extension<CustomColors>()!
                          .borderColor,
                    ),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    word,
                    style: Theme.of(context).textTheme.bodyLarge,
                  ),
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchHistory() {
    if (_historyItems.isNotEmpty) {
      return Container(
        decoration: BoxDecoration(
          border: Border(
            top: BorderSide(
              color: Theme.of(context).extension<CustomColors>()!.borderColor,
              width: 1,
            ),
          ),
        ),
        child: Column(
          children: _historyItems.map(
            (word) {
              return _buildHistroyItem(word['name'], word['id']);
            },
          ).toList(),
        ),
      );
    } else {
      return const SizedBox.shrink();
    }
  }

  Widget _buildHistroyItem(name, id) {
    return InkWell(
      onTap: () {
        _searchController.text = name;
        searchBtn();
      },
      splashColor: Colors.grey.withOpacity(0.3), // 水波纹颜色
      highlightColor: Colors.grey.withOpacity(0.1), // 按压高亮色
      child: Padding(
        padding: const EdgeInsets.symmetric(
          vertical: 0,
          horizontal: 12,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(
              Icons.schedule,
              size: 18,
              color: Theme.of(context).extension<CustomColors>()!.borderColor,
            ),
            const SizedBox(
              width: 12,
            ),
            Expanded(
              child: Container(
                padding: const EdgeInsets.symmetric(
                  vertical: 2,
                  horizontal: 0,
                ),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Theme.of(context)
                          .extension<CustomColors>()!
                          .borderColor,
                      width: 1,
                    ),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      name,
                      style: Theme.of(context).textTheme.bodyLarge,
                    ),
                    IconButton(
                      onPressed: () {
                        _deleteItem(id);
                      },
                      icon: Icon(
                        Icons.close,
                        size: 18,
                        color: Theme.of(context)
                            .extension<CustomColors>()!
                            .borderColor,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLeading() {
    return IconButton(
      onPressed: () {
        Get.back();
      },
      icon: Icon(
        Icons.arrow_back,
        size: 24,
        color: Theme.of(context).extension<CustomColors>()?.iconColor,
      ),
    );
  }

  Widget _buildSearchInput() {
    return TextFormField(
      focusNode: _focusNode,
      autofocus: true, // 自动获取焦点
      controller: _searchController,
      onFieldSubmitted: (value) => {
        searchBtn(),
      },
      // 输入文字样式
      style: Theme.of(context).textTheme.bodyLarge,
      // 光标颜色
      cursorColor: const Color(0x80FFFFFF),
      decoration: InputDecoration(
        hintText: '搜索音乐，歌手，歌词，用户',
        hintStyle: const TextStyle(
          color: Color(0x80FFFFFF),
          fontSize: 14,
          height: 1.0,
        ),
        // 关闭icon和搜索icon
        suffixIcon: Padding(
          padding: const EdgeInsets.only(right: 8.0),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 清除图标（根据文本显示/隐藏）
              if (_showClearIcon) ...[
                IconButton(
                  icon: Icon(
                    Icons.close,
                    size: 24,
                    color:
                        Theme.of(context).extension<CustomColors>()!.iconColor,
                  ),
                  onPressed: _clearText,
                ),
              ],
              if (_showSearchIcon) ...[
                Padding(
                  padding: const EdgeInsets.only(right: 8.0),
                  child: IconButton(
                    onPressed: () {
                      searchBtn();
                    },
                    icon: Icon(
                      Icons.search,
                      color: Theme.of(context)
                          .extension<CustomColors>()!
                          .iconColor,
                      size: 24,
                    ),
                  ),
                ),
              ]
            ],
          ),
        ),
        // 去掉默认的边框
        border: InputBorder.none,
        // 启用状态下的底部边框
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).extension<CustomColors>()!.iconColor,
          ),
        ),
        // 聚焦状态下的底部边框
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).extension<CustomColors>()!.iconColor,
          ),
        ),
        // 错误状态下的底部边框
        errorBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).extension<CustomColors>()!.iconColor,
          ),
        ),
        // 聚焦且错误状态下的底部边框
        focusedErrorBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).extension<CustomColors>()!.iconColor,
          ),
        ),
      ),
    );
  }
}
